<?php
/**
 * Created by PhpStorm.
 * User: zjx
 * Date: 2016/11/25
 * Time: 10:32
 */

namespace App\Services\Utils;

use App\Exceptions\AdminManageException;
use App\Services\AdminErrCode;


trait ApiChecker
{
    // API 请求参数错误
    protected function checkParamExist( $param , $tip = '')
    {
        if ( ! $param  ) {
            throw new AdminManageException( AdminErrCode::REQUEST_PARAMS_EMPTY, '参数'.$tip.'不能为空 | param must not empty');
        }
    }

    protected function checkParamInRange( $param , $range , $tip = '参数' )
    {
        if ( ! in_array( $param , $range )  ) {
            throw new AdminManageException( AdminErrCode::REQUEST_PARAMS_NOT_IN_RANGE, "{$tip}不在可选范围中 | param not in range");
        }
    }

    // 用户权限错误 4000 +
    /**
     * @param $authorizer
     * @throws AdminManageException
     */
    protected function checkAuthroizerExist($authorizer)
    {
        if ( ! $authorizer ) {
            throw new AdminManageException( AdminErrCode::AUTHORIZER_NOT_FOUND, '未找到授权公众号');
        }
    }
    
    protected function checkCanAccess($can_access)
    {
        if ( ! $can_access ) {
            throw new AdminManageException( AdminErrCode::ADMIN_AUTH_NOT_FOUND, '访问者无权访问 | user not able to access');
        }
    }

    protected function checkCanOperate( $editable , $tip = "操作者" )
    {
        if ( ! $editable ) {
            throw new AdminManageException( AdminErrCode::OPERATOR_NOT_ALLOWED , "此{$tip}无操作权限 | operator unauthorized ");
        }
    }


    // 服务端错误 5000 + 
    protected function checkItemExist( $item , $tip = "数据" , $code = null )
    {
        if ( ! $item ) {
            throw new AdminManageException(
                $code ?: AdminErrCode::DB_ITEM_NOT_FOUND ,
                "你所查找的{$tip}不存在 | item not found in db"
            );
        }
    }

    protected function checkItemEditable( $editable , $tip = "数据" )
    {
        if ( ! $editable ) {
            throw new AdminManageException(
                AdminErrCode::DB_NOT_EDITABLE ,
                "你所查找的{$tip}已锁定，不能修改 | item locked can not be modified "
            );
        }
    }

    protected function checkOperateSuccess( $success , $tip = "项目" )
    {
        if ( ! $success ) {
            throw new AdminManageException( AdminErrCode::OPERATE_FAILED , "执行{$tip}操作失败，请检查 | item modify failed ");
        }
    }

    /**
     * @param bool $is_ok
     * @param int $code
     * @param string $tip
     * @throws AdminManageException
     */
    protected function checkUndefinedError($is_ok, $code = AdminErrCode::UNKNOWN_ERROR , $tip = "执行未知操作失败")
    {
        if (! $is_ok) {
            throw new AdminManageException($code , $tip);
        }
    }


}